<?php
/**
 * Localisation city Model.
 *
 * @copyright  2016 opencart.cn - All Rights Reserved
 * @link       http://www.guangdawangluo.com
 * @author     Edward Yang <yangjin@opencart.cn>
 * @created    2016-11-10 11:39:20
 * @modified   2016-11-10 11:58:58
 */

class ModelLocalisationCity extends Model
{
    public function addCity($data)
    {
        $this->db->query("INSERT INTO " . DB_PREFIX . "city SET name = '" . $this->db->escape($data['name']) . "', up_id='" . (int)$data['parent_id'] . "', zone_id = '" . (int)$data['zone_id'] . "', status = '" . (int)$data['status'] . "'");

        $this->cache->delete('city');
    }

    public function getCityByName($name, $zoneId = null)
    {
        if ($zoneId) {
            $sql = "SELECT * FROM " . DB_PREFIX . "city WHERE name = '" . $name . "' AND zone_id=" . (int)$zoneId;
        } else {
            $sql = "SELECT * FROM " . DB_PREFIX . "city WHERE name = '" . $name . "'";
        }
        $query = $this->db->query($sql);
        return $query->row;
    }

    public function getCountyByName($name, $cityId)
    {
        if ($cityId) {
            $sql = "SELECT * FROM " . DB_PREFIX . "city WHERE name = '" . $name . "' AND up_id=" . (int)$cityId;
        } else {
            return null;
        }
        $query = $this->db->query($sql);
        return $query->row;
    }

    public function editCity($city_id, $data)
    {
        $this->db->query("UPDATE " . DB_PREFIX . "city SET name = '" . $this->db->escape($data['name']) . "', up_id='" . (int)$data['parent_id'] . "', zone_id = '" . (int)$data['zone_id'] . "', status = '" . (int)$data['status'] . "' WHERE city_id = '" . (int)$city_id . "'");

        $this->cache->delete('city');
    }

    public function deleteCity($city_id)
    {
        $this->db->query("DELETE FROM " . DB_PREFIX . "city WHERE city_id = '" . (int)$city_id . "'");

        $this->cache->delete('city');
    }

    public function getCity($city_id)
    {
        $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "city WHERE city_id = '" . (int)$city_id . "'");

        return $query->row;
    }

    public function getCities($data = array())
    {
        if ($data) {
            $sql = "SELECT c.city_id AS city_id, c.zone_id AS zone_id, c.name AS name, c.status AS status, (SELECT name FROM " . DB_PREFIX . "zone z WHERE z.zone_id = c.zone_id AND z.status = '1') AS zone FROM " . DB_PREFIX . "city c";
            if (isset($data['filter_name']) && $data['filter_name']) {
                $sql .= " where c.name like '%" . $data['filter_name'] . "%'";
            }
            $sort_data = array(
                'name',
                'zone'
            );

            if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
                $sql .= " ORDER BY " . $data['sort'];
            } else {
                $sql .= " ORDER BY zone";
            }

            if (isset($data['order']) && ($data['order'] == 'DESC')) {
                $sql .= " DESC";
            } else {
                $sql .= " ASC";
            }

            if (isset($data['start']) || isset($data['limit'])) {
                if ($data['start'] < 0) {
                    $data['start'] = 0;
                }

                if ($data['limit'] < 1) {
                    $data['limit'] = 20;
                }

                $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
            }

            $query = $this->db->query($sql);

            return $query->rows;
        } else {
            $city_data = $this->cache->get('city');

            if (!$city_data) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "city ORDER BY name ASC");

                $city_data = $query->rows;

                $this->cache->set('city', $city_data);
            }

            return $city_data;
        }
    }

    public function getCitiesByZoneId($zoneId, $topLevel = true)
    {
        $cacheKey = 'city.' . (int)$zoneId . '_' . (int)$topLevel;
        $city_data = $this->cache->get($cacheKey);

        if (!$city_data) {
            if ($topLevel) {
                $sql = "SELECT * FROM " . DB_PREFIX . "city WHERE zone_id = '" . (int)$zoneId . "' AND status = '1' AND up_id=0 ORDER BY name";
            } else {
                $sql = "SELECT * FROM " . DB_PREFIX . "city WHERE up_id = '" . (int)$zoneId . "' AND status = '1' ORDER BY name";
            }
            $query = $this->db->query($sql);

            $city_data = $query->rows;
            $this->cache->set($cacheKey, $city_data);
        }

        return $city_data;
    }

    public function generateAddressCity($data)
    {
        $addressCity = '';
        if (isset($data['city_id']) && (int)$data['city_id'] > 0) {
            $city = $this->getCity($data['city_id']);
            $addressCity = $city['name'];
        }
        if (isset($data['county_id']) && (int)$data['county_id'] > 0) {
            $county = $this->getCity($data['county_id']);
            $addressCity = $addressCity . ' ' . $county['name'];
        }
        return $addressCity;
    }

    public function getCityIdFromAddress($data)
    {
        if (!isset($data['city'])) {
            return 0;
        }
        $cityDistrict = explode(' ', $data['city']);
        $city = $this->getCityByName($cityDistrict[0], $data['zone_id']);
        if (empty($city)) {
            return null;
        }
        return $city['city_id'];
    }

    public function getCountyIdFromAddress($data)
    {
        if (!isset($data['city'])) {
            return 0;
        }
        $cityDistrict = explode(' ', $data['city']);
        if (!isset($cityDistrict[1])) {
            return null;
        }
        $cityId = $this->getCityIdFromAddress($data);
        if (!$cityId) {
            return null;
        }
        $city = $this->getCountyByName($cityDistrict[1], $cityId);
        if (empty($city)) {
            return null;
        }
        return $city['city_id'];
    }

    public function getTotalCities($filter_data = array())
    {
        if (!$filter_data) {
            $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "city");
        } else {
            if ($filter_data['filter_name']) {
                $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "city where name like '%" . $filter_data['filter_name'] . "%'");
            } else {
                $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "city");
            }
        }
        return $query->row['total'];
    }

    public function checkDatabase()
    {
        $query = $this->db->query("SHOW TABLES LIKE '" . DB_PREFIX . "city'");

        if (!$query->num_rows) {
            $this->db->query("CREATE TABLE `" . DB_PREFIX . "city` (`city_id` int(11) NOT NULL AUTO_INCREMENT, `zone_id` int(11) NOT NULL, `name` varchar(128) NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1', `sort_order` int(3) NOT NULL DEFAULT '0', PRIMARY KEY (`city_id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;");

            $this->db->query(
                "INSERT INTO `" . DB_PREFIX . "city` (`zone_id`, `name`, `status`) VALUES
				(1, 'test', 1),
				(2, 'test2', 1);"
            );
        }
    }
}
